//
//  FPCinemaDetailViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/21.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPCinemaDetailViewController.h"
#import "FPCinemaDetailView.h"
#import "FPCinemaDetailTableViewCell.h"
#import "FPCinemaDetailModel.h"
#import "BMapKit.h"
#define kDetailUrl @"http://api.m.mtime.cn/Cinema/Detail.api?cinemaId=%@"

@interface FPCinemaDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) FPCinemaDetailView *fpcinemaDetailView;
@property (nonatomic, strong) FPCinemaDetailTableViewCell *fpCinemaDetailTVC;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *featureArray;
@property (nonatomic, strong) NSMutableArray *galleryArray;
@property (nonatomic, strong) NSArray *feaAllKeys;
@property (nonatomic, strong) NSArray *feaValues;
@property (nonatomic, strong) NSMutableDictionary *cellDic;
@property (nonatomic, strong) UIView *statusBarView;
@property (nonatomic, strong) NSString *telStr;
@property (nonatomic, strong) MBProgressHUD * HUD;
@end

@implementation FPCinemaDetailViewController
-(UIView *)statusBarView
{
    if (!_statusBarView) {
        _statusBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
        [self.view addSubview:_statusBarView];

    }
    return _statusBarView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    label.text = @"影院详情";
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    
    // 隐藏navigation下面的黑线
    [self hideNavigationBlackLine];
    
    // 返回 button
    [self backButton];
    
    // 创建顶部背景图
    [self B_tableView];
    
    
    
    // 加载数据
    [self setUrl];
  
}

- (void)loadView
{
//    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//    self.scrollView.contentSize = CGSizeMake(0, kScreenHeight);
    
    self.fpcinemaDetailView = [[FPCinemaDetailView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(350))];
    self.fpcinemaDetailView.scrollView.delegate = self;
    self.view = _fpcinemaDetailView;
}
/*==============================================解析数据============================================*/
- (void)setUrl
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view bringSubviewToFront:_HUD];
    if ([[FPNetWork shareInstance] rechability]) {
        self.HUD.labelText = @"正在加载";
        // 解析数据
        [self B_analisisModel];
        
    }
    else
    {
        self.HUD.labelText = @"请检查网络";
    }
    
    
}


- (void)B_analisisModel
{
    // 初始化数组
    self.modelArray   = [NSMutableArray array];
    self.featureArray = [NSMutableArray array];
    self.galleryArray = [NSMutableArray array];
    self.feaAllKeys   = [NSArray array];
    self.feaValues    = [NSArray array];
    self.cellDic      = [NSMutableDictionary dictionary];
    
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:kDetailUrl,_kUrl]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    // 开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if (data == nil) return ;
                               NSMutableDictionary *modelDic = [NSJSONSerialization JSONObjectWithData:data
                                                                                               options:NSJSONReadingMutableContainers
                                                                                                 error:nil];
                               FPCinemaDetailModel *model = [FPCinemaDetailModel cinemaDetailModelWithDictionary:modelDic];
                               _fpcinemaDetailView.addressLabel.text      = model.address;
                               _fpcinemaDetailView.telLabel.text          = model.tel;
                               _telStr                                    = model.tel;
                               _fpcinemaDetailView.cinemaNameLabel.text   = model.name;
                               _fpcinemaDetailView.numberCinemaLabel.text = [NSString stringWithFormat:@"%ld",(long)model.hallCount];
                               _fpcinemaDetailView.ratingLabel.text       = [NSString stringWithFormat:@"%.0f%%",model.rating * 10.0];
                               _fpcinemaDetailView.filmResulLabel.text    = [NSString stringWithFormat:@"观影效果:%.1f",model.qualityRating];
                               _fpcinemaDetailView.filmQualityLabel.text  = [NSString stringWithFormat:@"服务质量:%.1f",model.serviceRating];
                               [_fpcinemaDetailView.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.image] completed:nil];
//                               [_fpcinemaDetailView.markButton addTarget:self action:@selector(markButtonAction) forControlEvents:UIControlEventTouchUpInside];
                               // 添加轻拍手势
                               [self addTapGesture];
                               [self.modelArray addObject:model];
                               NSDictionary *featureDic = [modelDic objectForKey:@"feature"];
                               self.feaAllKeys = [featureDic allKeys];
                               self.feaValues  = [featureDic allValues];
                               for (int i = 0; i < _feaValues.count; i ++) {
                                   NSString *str = [NSString stringWithFormat:@"%@",self.feaValues[i]];
                                   if (![str isEqualToString:@""] && ![str isEqualToString:@"0"] && ![str isEqualToString:@"1"]) {
                                       [_cellDic setValue:_feaValues[i] forKey:_feaAllKeys[i]];
                                   }
                               }
                               FPCinemaDetailModel *featureModel = [FPCinemaDetailModel cinemaDetailModelWithDictionary:featureDic];
                               [self.featureArray addObject:featureModel];
                               
                               NSArray *array = [modelDic objectForKey:@"galleryList"];
                               [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
                                   FPCinemaDetailModel *model = [FPCinemaDetailModel cinemaDetailModelWithDictionary:dic];
                                   [self.galleryArray addObject:model];
                               }];
                               [self.tableView reloadData];
                               [self.HUD hide:YES afterDelay:1];
                           }];
}
/*==============================================方法实现============================================*/
- (void)backButton
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 30, 30, 30);
    [btn setTitle:@"返回" forState:UIControlStateNormal];
    btn.tintColor = [UIColor whiteColor];
    [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
- (void)btnAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)markButtonAction
{
    NSLog(@"点击了我要 评分 ");
}

- (void)addTapGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dialPhone)];
    [_fpcinemaDetailView.telLabel addGestureRecognizer:tap];
}

// 调用手机拨号盘
- (void)dialPhone
{
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",_telStr]];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
}

- (void)gotoMap
{
    BMKOpenTransitRouteOption *opt = [[BMKOpenTransitRouteOption alloc] init];
    //    opt.appName = @"SDK调起Demo";
    opt.appScheme = @"baidumapsdk://mapsdk.baidu.com";
    //初始化起点节点
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    //指定起点经纬度
    CLLocationCoordinate2D coor1;
    coor1.latitude = 39.90868;
    coor1.longitude = 116.204;
    //指定起点名称
    start.name = @"当前位置";
    start.pt = coor1;
    //指定起点
    opt.startPoint = start;
    
    //初始化终点节点
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = 39.90868;
    coor2.longitude = 116.3956;
    end.pt = coor2;
    //指定终点名称
    end.name = _fpcinemaDetailView.cinemaNameLabel.text;
    opt.endPoint = end;
    
    BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapTransitRoute:opt];
    NSLog(@"%d", code);
    return;
}

// 隐藏Navigation下面的黑线
- (void)hideNavigationBlackLine
{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView = (UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    UIImageView *imageView2 = (UIImageView *)obj2;
                    imageView2.hidden = YES;
                }
            }
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    (_fpcinemaDetailView.scrollView.contentOffset.y < kImageH(50)) ? (_fpcinemaDetailView.scrollView.bounces = NO) : (_fpcinemaDetailView.scrollView.bounces = YES);
    UIColor *color = [UIColor colorWithRed:0.180 green:0.596 blue:1.000 alpha:1.000];
    CGFloat offsetY = scrollView.contentOffset.y;
   
    if (offsetY > 0) {
        CGFloat alpha = 1 - (44 - offsetY) / 44;
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:alpha];
        
        [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        self.statusBarView.backgroundColor = [color colorWithAlphaComponent:alpha];
        
        [self setNeedsStatusBarAppearanceUpdate];
    }else{
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:0];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
        self.statusBarView.backgroundColor = [color colorWithAlphaComponent:0];
        [self setNeedsStatusBarAppearanceUpdate];;
    }

}

/*==============================================创建视图============================================*/
// 创建tableview
- (void)B_tableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kImageH(350), kScreenWidth, kScreenHeight - kImageH(350))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = [self headerView];
    [_fpcinemaDetailView.scrollView addSubview:_tableView];
}

- (UIView *)headerView
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 200, 30)];
    label.text = @"  特色设施";
    label.font = [UIFont systemFontOfSize:18.0 weight:2.0];
    return label;
    
}

/*==============================================tableView===========================================*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
       
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [_cellDic allValues];
    return array.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [tableView registerClass:[FPCinemaDetailTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    FPCinemaDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    NSArray *array      = [_cellDic allValues];
    NSString *str       = array[indexPath.row];
//    NSArray *imageArray = @[@"C_icon1",@"C_icon2",@"C_icon3",@"C_icon4",@"C_icon5",@"C_icon6",@"C_icon7",@"C_icon8",@"C_icon9",@"C_icon10"];
//    NSString *imageStr  = imageArray[indexPath.row];
    cell.contentLabel.text = str;
    cell.iconImageView.image = [UIImage imageNamed:@"C_icon"];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
